# -*- coding: UTF-8 -*-
# 加验证准备版
import docx
from docx import Document        #导入读取word模块
import os
import os.path
from  openpyxl import *          #导入读写excel模块
from pythonwin import win32ui    #导入打开文件选择框模块
import re
import win32com
from win32com.client import Dispatch
from win32com import client as wc
#class Word():
input('选择产品验证方案-回车继续')
word = wc.gencache.EnsureDispatch('Word.Application')
dlg = win32ui.CreateFileDialog(1)         #1表示打开文件对话框
dlg.SetOFNInitialDir('C:/Users')          #设置打开文件对话框中的初始显示目录
dlg.DoModal()
WordName = dlg.GetPathName()               #获取选择的文件名称
Path_l = os.path.join(os.path.dirname(WordName))
print(Path_l)
print(WordName)
Path = os.path.join(os.getcwd(),WordName)    #获取选择的文件路径

'''新建word'''
print("复制中，请稍等")
new_doc = Document()
wo_name = Path_l + '\第二个验证方案文档'+'.docx'
new_doc.save(wo_name)
try:
    '''复制表格'''
    app = win32com.client.DispatchEx('Word.Application')
    # 打开word，经测试要是绝对路径
    print("pass1")
    doc = app.Documents.Open(Path)
    print("pass2")
    # 复制word的所有内容
    doc.Content.Copy()
    print("pass13")
    # 关闭word
    doc.Close()
    print("pass14")
except Exception:
        print("复制失败")
        doc.Close()
try:
    word = win32com.client.DispatchEx('Word.Application')
    doc1 = word.Documents.Open(wo_name)
    s = word.Selection
    s.MoveRight(1, doc1.Content.End) # 将光标移动到文末，就这一步试了我两个多小时
    s.Paste()
    doc1.Close()
except Exception:
        print("粘贴失败")
        doc1.Close()

'''
#复制一个文档保存
word.Visible = False
doc = word.Documents.Open(Path)
doc_name = Path_l + '\需去除修订文件'+'.docx'
print(doc_name)
doc.SaveAs(doc_name)
doc.Close()
input('1.在需要提取追溯表word目录下，找到需去除修订文件.docx\n 2.顶部菜单栏点击"审阅"-"修订"-"锁定修订"（使修订锁定取消）\n 3.点击修订右侧"接受"-"接受所有修订"\n 4.保存关闭word \n 5.在此处按回车键继续')
'''
num1 = int(input("请输入你想从第几个表格开始拉取数据："))
num2 = num1 - 1
document = Document(wo_name) #读入文件
tables = document.tables #获取文件中的表格集
table_num=len(tables)#获取文档的表格个数
print(table_num)
name = [];
number1 = [];
number2 = [];
zhunbei = [];
num3 = input("请输入您想要跳过的表格（1.可以输入 NO 不跳过，后续在表格内手动删除 \n ）：")
print(num3)
if num3 == 'NO':
    for k in range(num2,table_num):
        try:
            yongli = tables[k].cell(1,2).text#获取第i张表第2行第2列数据
        except Exception:
            yongli = "当前表格无对应行列位置"
        try:
            mingcheng = tables[k].cell(2,2).text  #获取第i张表第3行第2列数据
        except Exception:
            mingcheng = "当前表格无对应行列位置"
        try:
            xvqiu = tables[k].cell(4,2).text #获取第i张表第5行第2列数据
        except Exception:
            xvqiu = "当前表格无对应行列位置"
        try:
            zhunbei2 = tables[k].cell(7,2).text #获取第i张表第5行第2列数据
        except Exception:
            zhunbei2 = "当前表格无对应行列位置"
        name.append(yongli)
        number1.append(mingcheng)
        number2.append(xvqiu)
        zhunbei.append(zhunbei2)
    print(name)
    print(number1)
    print(number2)
    print(zhunbei)
else:
    num3_list = num3.split(' ')
    num3_len = len(num3_list)
    # num3_list = [int(num3_list[i]) for i in range(num3_len)]
    print(num3_len)
    for k in range(num2,table_num):
        a=0
        while a<num3_len:
            b = num3_list[a]
            print(b)
            b = int(b)-1
            if k == b:
                break 
            else:
                a=a+1
        # for a in range(num3_len):
        #     num_skip = num3_list[a]
        #     if k == num_skip:
        #          跳出这个循环
        # else:
        try:
            yongli = tables[k].cell(1,2).text#获取第i张表第2行第2列数据
        except Exception:
            yongli = "当前表格无对应行列位置"
        try:
            mingcheng = tables[k].cell(2,2).text  #获取第i张表第3行第2列数据
        except Exception:
            mingcheng = "当前表格无对应行列位置"
        try:
            xvqiu = tables[k].cell(4,2).text #获取第i张表第5行第2列数据
        except Exception:
            xvqiu = "当前表格无对应行列位置"
        name.append(yongli)
        number1.append(mingcheng)
        number2.append(xvqiu)
                
    print(name)
    print(number1)
    print(number2)

from openpyxl import  Workbook 
from openpyxl import workbook
from openpyxl import load_workbook
#新建excel
wb = Workbook() # 实例化
ws = wb.active  # 激活 worksheet
###打开已有excel表格
##wb = load_workbook('../TEST.xlsx')
##ws = wb["Sheet1"]
length = len(name)
print('共计 ',length,' 行数据')
for i in range(1,length+1,1):
   ws.cell(row=i+1, column=1, value=name[i-1])#row：行    column：列    value：内容
   ws.cell(row=i+1, column=2, value=number1[i-1])#row：行    column：列    value：内容
   ws.cell(row=i+1, column=3, value=number2[i-1])#row：行    column：列    value：内容
   ws.cell(row=i+1, column=4, value=zhunbei[i-1])#row：行    column：列    value：内容
ws.cell(row=1, column=1, value='TC_用例编号')# 加上标题
ws.cell(row=1, column=2, value='TC_用例名称')
ws.cell(row=1, column=3, value='TC_需求编号')
ws.cell(row=1, column=4, value='TC_验证准备')
ex_name = Path_l + '\追溯对照表'+'.xlsx'
wb.save(ex_name)    
print('产品验证方案提取完成！')
input('回车继续提取PRS文档')

"""分割线"""
word = wc.gencache.EnsureDispatch('Word.Application')
dlg = win32ui.CreateFileDialog(1)         #1表示打开文件对话框
dlg.SetOFNInitialDir('C:/Users')          #设置打开文件对话框中的初始显示目录
dlg.DoModal()
WordName = dlg.GetPathName()               #获取选择的文件名称
Path_l2 = os.path.join(os.path.dirname(WordName))
print(Path_l2)
print(WordName)
Path = os.path.join(os.getcwd(),WordName)    #获取选择的文件路径

'''
word.Visible = False
doc = word.Documents.Open(Path)
doc_name = Path_l2 + '\需去除修订文件'+'.docx'
print(doc_name)
doc.SaveAs(doc_name)
doc.Close()
input('1.在需要提取追溯表word目录下，找到需去除修订文件.docx\n 2.顶部菜单栏点击"审阅"-"修订"-"锁定修订"（使修订锁定取消）\n 3.点击修订右侧"接受"-"接受所有修订"\n 4.保存关闭word \n 5.在此处按回车键继续')
'''

'''新建word'''

new_doc = Document()
name2 = Path_l2 + '\第二个PRS文档'+'.docx'
new_doc.save(name2)

try:
    '''复制表格'''
    app = win32com.client.DispatchEx('Word.Application')
    # 打开word，经测试要是绝对路径
    doc = app.Documents.Open(Path)
    # 复制word的所有内容
    doc.Content.Copy()
    # 关闭word
    doc.Close()
except Exception:
        print("复制失败")
        doc.Close()

try:
    word = win32com.client.DispatchEx('Word.Application')
    doc1 = word.Documents.Open(name2)
    s = word.Selection
    s.MoveRight(1, doc1.Content.End) # 将光标移动到文末，就这一步试了我两个多小时
    s.Paste()
    doc1.Close()
except Exception:
        print("粘贴失败")
        doc1.Close()

num1 = int(input("请输入你想从第几个表格开始拉取数据："))
num2 = num1 - 1
document = Document(name2) #读入文件
tables = document.tables #获取文件中的表格集
table_num=len(tables)#获取文档的表格个数
print(table_num)
name = [];
number3 = [];
num3 = input("请输入您想要跳过的表格（可以输入NO不跳过，后续在表格内手动删除）：")
print(num3)
if num3 == 'NO':
    for k in range(num2,table_num):
        num_li =len(tables[k].rows)
        for i in range(1,num_li):
            try:
                PRS_number = tables[k].cell(i,0).text#获取第i张表第2行第2列数据
            except Exception:
                PRS_number = "当前表格无对应行列位置"
            try:
                PRS_name = tables[k].cell(i,1).text#获取第i张表第2行第2列数据
            except:
                PRS_name = "当前表格无对应行列位置"

            name.append(PRS_name)
            number3.append(PRS_number)
    print(name)
    print(number3)
else:
    num3_list = num3.split(' ')
    num3_len = len(num3_list)
    # num3_list = [int(num3_list[i]) for i in range(num3_len)]
    print(num3_len)
    for k in range(num2,table_num):
        a=0
        while a<num3_len:
            b = num3_list[a]
            print(b)
            b = int(b)-1
            if k == b:
                break 
            else:
                a=a+1
        # for a in range(num3_len):
        #     num_skip = num3_list[a]
        #     if k == num_skip:
        #          跳出这个循环
        # else:
    for k in range(num2,table_num):
        try:
            PRS_number = tables[k].cell(1,1).text#获取第i张表第2行第2列数据
        except Exception:
            PRS_number = "当前表格无对应行列位置"
        try:
            PRS_name = tables[k].cell(1,2).text#获取第i张表第2行第2列数据
        except:
            PRS_name = "当前表格无对应行列位置"

        name.append(PRS_name)
        number3.append(PRS_name)
                
    print(name)
    print(number3)
    print("请保持追溯表excel为关闭状态，打开中会导致无法写入数据")
    input('回车继续')
from openpyxl import workbook
from openpyxl import load_workbook
#新建excel
wb = Workbook() # 实例化
ws = wb.active  # 激活 worksheet
###打开已有excel表格
wb = load_workbook(ex_name)
ws = wb["Sheet"]
length = len(name)
print('共计 ',length,' 行数据')
for i in range(1,length+1,1):
    ws.cell(row=i+1, column=6, value=number3[i-1])#row：行    column：列    value：内容
    ws.cell(row=i+1, column=7, value=name[i-1])#row：行    column：列    value：内容
ws.cell(row=1, column=6, value='PRS_需求编号')
ws.cell(row=1, column=7, value='PRS_需求名称')
ex_name = Path_l + '\追溯对照表'+'.xlsx'
wb.save(ex_name)    
os.remove(wo_name)
os.remove(name2)
print('PRS提取完成！')
input('文件位于方案所在目录“追溯对照表”   按回车结束')